String.prototype.Trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

// var vm = new Vue({
//     el: '#app',
//     created: function () {
//         var that = this;
//
//         $.ajax({
//             'url': '/trainPlatform/knowledge_items.do',
//             'success': function (resp) {
//                 if (resp.success) {
//                     that.knowledge_items = resp.data;
//                     that.selected = that.knowledge_items[0];
//                 }
//             }
//         });
//     },
//     data: {
//         knowledge_items: [],
//         selected: '',
//         searchKw: '',
//         lastSearchKw: ''
//     },
//     computed: {},
//     methods: {
//         'select': function (i) {
//             $.ajax({
//                 'url': '/trainPlatform/knowledge_value.do',
//                 'data': {
//                     'key': i
//                 },
//                 'success': function (resp) {
//                     if (resp.success) {
//
//                     }
//                 }
//             })
//         },
//         'searchInput': function () {
//             if (this.searchKw == this.lastSearchKw) {
//                 return;
//             }
//
//             this.lastSearchKw = this.searchKw;
//
//             var that = this;
//
//             $.ajax({
//                 'url': '/trainPlatform/knowledge_items.do',
//                 'data': {
//                     kw: this.searchKw
//                 },
//                 'success': function (resp) {
//                     if (resp.success) {
//                         that.knowledge_items = resp.data;
//                     }
//                 }
//             });
//         }
//     },
//     components: {}
// });

function knowledge_items(kw) {
    $.ajax({
        'url': '/trainPlatform/knowledge_items.do',
        'data': {
            kw: $('#search-input').val().Trim()
        },
        'success': function (resp) {
            if (resp.success) {
                var html = "";

                for (var i = 0; i < resp.data.length; i++) {
                    html += '<div class = "knowledge_item">\n' +
                        '                            <div class = "mdui-chip ml5">\n' +
                        '                                <span class = "mdui-chip-title f13">' + resp.data[i] + '</span>\n' +
                        '                            </div>\n' +
                        '                        </div>'
                }

                $('.knowledge_items_containers').html(html);
            }
        }
    });
}

knowledge_items()

var data = null;

var stage = new Konva.Stage({
    container: 'container',
    width: 2000,
    height: 2000
});

var layer = new Konva.Layer({
    draggable: true
});

stage.add(layer);

var cur_selected = null;
var cur_item = null;

$('#search-input').on('input', function (e) {
    if (cur_selected) {
        cur_selected.fire('unselected');
    }

    cur_selected = null;
    cur_item = null;

    clear_screen();

    knowledge_items($('#search-input').val());
});

$('body').delegate('.knowledge_item', 'click', function (e) {
    SynonymList([]);

    $(e.target).closest('.mdui-chip').addClass('mdui-color-indigo').parent().siblings().find('.mdui-color-indigo').removeClass('mdui-color-indigo');

    var key = $(e.target).closest('.knowledge_item').find('.mdui-chip-title').text();

    if (cur_selected) {
        cur_selected.fire('unselected');
    }

    cur_item = null;
    cur_selected = null;

    $.ajax({
        'url': '/trainPlatform/knowledge_search.do',
        'data': {
            'key': key
        },
        'success': function (resp) {
            if (resp.success) {
                // 清除界面
                clear_screen();

                data = resp.data;

                init_data(resp.data);

                iter(resp.data);
            } else {
                alert(resp.msg);
            }
        }
    });
});

function SynonymList(nodes) {
    var html = "";
    for (var i = 0; i < nodes.length; i++) {
        html += '<div class = "mdui-chip ml5 symItem"><span class = "mdui-chip-title f13">' + nodes[i] + '</span><i class = "mr10 mdui-icon material-icons f13 delSymItem">close</i></div>'
    }
    html += '<i class = "ml10 mdui-icon material-icons" style = "color:#e0e0e0;cursor: pointer;" id = "addSyn">add_circle</i>';

    $('.SynonymList').html(html);
}

$('body').delegate('.symItem', 'contextmenu', function (e) {
    e.preventDefault();

    $('#ctx-menu2').css({
        'left': e.clientX,
        'top': e.clientY
    });

    inst2.open();

    e.stopPropagation();
});

$('body').delegate('.symItem .delSymItem', 'click', function (e) {
    if (!cur_item) {
        return;
    }

    var symText = $(e.target).closest('.mdui-chip').find('.mdui-chip-title').text();

    mdui.dialog({
        title: '同义节点删除提醒',
        content: '您正在删除' + cur_item['key'] + '与' + symText + '的同义关系，确定吗?',
        buttons: [
            {
                text: '取消'
            },
            {
                text: '确认',
                onClick: function (inst) {
                    if (!cur_item) {
                        return;
                    }

                    $.ajax({
                        'url': '/trainPlatform/delSynonym.do',
                        'data': {
                            'root': cur_item['key'],
                            'leaf': symText
                        },
                        'success': function (resp) {
                            if (resp.success) {
                                $(e.target).closest('.mdui-chip').remove();

                                cur_selected = null;
                                cur_item = null;
                            }
                        }
                    })
                }
            }
        ]
    });
});

$('body').delegate('#addSyn', 'click', function () {
    if (!cur_item) {
        return alert('请您先点击选中节点');
    }

    mdui.prompt('同义节点', '节点名称', function (text) {
            text = text.Trim().toLowerCase();

            $.ajax({
                'url': '/trainPlatform/addSynonym.do',
                'data': {
                    root: cur_item['key'],
                    leaf: text
                },
                'success': function (resp) {
                    if (resp.success) {
                        cur_item.alias.push(text);

                        // 重新绘制同义词列表
                        SynonymList(cur_item.alias);
                    }
                }
            });
        }, function (text) {
        },
        {
            'confirmText': '确定',
            'cancelText': '取消',
            'defaultValue': ''
        });
});

// SynonymList(['node.js', 'c++', 'android']);

$('#newNode').click(function (e) {
    mdui.prompt('节点名称', '构造新节点', function (text) {
        text = text.Trim().toLowerCase();

        $.ajax({
            'url': '/trainPlatform/newNode.do',
            'data': {
                name: text
            },
            'success': function (resp) {
                if (resp.success) {
                    clear_screen();

                    cur_item = null;
                    cur_selected = null;

                    data = {
                        'key': text.Trim(),
                        'alias': [],
                        'value': [],
                        'selected': false,
                        'x': -1,
                        'y': -1,
                        'nid': Math.floor(Math.random() * 10000 + 1)
                    };

                    iter(data);

                    $(".knowledge_item").removeClass('mdui-color-indigo');

                    $.each($('.knowledge_item'), function (i, e) {
                        if ($(e).find('.mdui-chip').hasClass('mdui-color-indigo')) {
                            $(e).remove();
                        }
                    });
                } else {
                    alert(resp.msg);
                }
            }
        });
    }, function (text) {
    }, {
        'confirmText': '确定',
        'cancelText': '取消',
        'defaultValue': ''
    });
});

function clear_selected(data) {
    if (!data) {
        return;
    }

    data['selected'] = false;

    for (var i = 0; i < data['value'].length; i++) {
        clear_selected(data['value'][i]);
    }
}

function init_data(data, pnid) {
    if (!data) {
        return;
    }

    data['selected'] = false;
    data['x'] = -1;
    data['y'] = -1;
    data['nid'] = Math.floor(Math.random() * 10000 + 1);

    if (pnid) {
        data['pnid'] = pnid;
    }

    for (var i = 0; i < data['value'].length; i++) {
        init_data(data['value'][i], data['nid']);
    }
}

function find_item_by_nid(data, nid) {
    if (data['nid'] == nid) {
        return data;
    }

    for (var i = 0; i < data['value'].length; i++) {
        var item = find_item_by_nid(data['value'][i], nid);

        if (item) {
            return item;
        }
    }

    return;
}

function clear_screen() {
    var Rects = stage.find('Rect');
    var Arrows = stage.find('Arrow');

    for (var i = 0; i < Rects.length; i++) {
        Rects[i].destroy();
    }

    for (var i = 0; i < Arrows.length; i++) {
        Arrows[i].destroy();
    }

    layer.draw();
}

function iter(data, parent) {
    if (data.hidden) {
        return;
    }

    draw_knowledge_items(data, parent);

    for (var i = 0; i < data['value'].length; i++) {
        if (data['value'][i]['value'].length) {
            iter(data['value'][i], data['key']);
        }
    }
}

function draw_knowledge_items(data, parent) {
    if (data.hidden) {
        return;
    }

    // 如果parent为空则说明是根节点
    if (!parent) {
        var key_text = node(null, data, 0, 20, 20);
    } else {
        var key_text = stage.findOne('#' + data['key']);
    }

    if (!key_text) {
        return;
    }

    if (!key_text['arrows']) {
        key_text['arrows'] = [];
    }

    // 绘制子节点
    for (var i = 0; i < data['value'].length; i++) {
        node(key_text, data['value'][i], i);
    }

    layer.draw();
}

function node(key_text, item, i, x, y) {
    if (item['hidden']) {
        return;
    }

    var group = new Konva.Group();

    var text_ = new Konva.Text({
        x: x ? x : (item['x'] == -1 ? key_text.attrs.x + key_text.getWidth() + 100 : item['x']),
        y: y ? y : (item['y'] == -1 ? key_text.attrs.y + 80 * i : item['y']),
        text: item['key'] ? item['key'] : '点我编辑',
        fontSize: 14,
        fontFamily: 'Calibri',
        fill: '#fff',
        padding: 12,
        align: 'center',
        draggable: true,
        id: item['key'],
        nid: item['nide']
    });

    var rect_ = new Konva.Rect({
        x: text_.attrs.x,
        y: text_.attrs.y,
        fill: '#3f51b5',
        width: text_.getWidth(),
        height: text_.getHeight()
    });

    text_['selected'] = item['selected'] ? item['selected'] : false;

    if (text_['selected']) {
        cur_selected = text_;
        cur_item = item;
    }

    var rect_left_top = new Konva.Rect({
        x: rect_.attrs.x - 4,
        y: rect_.attrs.y - 4,
        id: 'rect_left_top',
        fill: '#ccc',
        width: 8,
        height: 8,
        opacity: text_['selected'] ? 1 : 0
    });

    var rect_left_bottom = new Konva.Rect({
        x: rect_.attrs.x - 4,
        y: rect_.attrs.y + rect_.attrs.height - 4,
        fill: '#ccc',
        id: 'rect_left_bottom',
        width: 8,
        height: 8,
        opacity: text_['selected'] ? 1 : 0
    });

    var rect_right_top = new Konva.Rect({
        x: rect_.attrs.x + rect_.attrs.width - 4,
        y: rect_.attrs.y - 4,
        fill: '#ccc',
        id: 'rect_right_top',
        width: 8,
        height: 8,
        opacity: text_['selected'] ? 1 : 0
    });

    var rect_right_bottom = new Konva.Rect({
        x: rect_.attrs.x + rect_.attrs.width - 4,
        y: rect_.attrs.y + rect_.attrs.height - 4,
        fill: '#ccc',
        id: 'rect_right_bottom',
        width: 8,
        height: 8,
        opacity: text_['selected'] ? 1 : 0
    });

    // 如果存在父节点，则绘制一条箭头从父节点指向本节点
    if (key_text) {
        var start_x = key_text.attrs.x + key_text.getWidth();
        var start_y = key_text.attrs.y + key_text.getHeight() / 2;

        var end_x = rect_.attrs.x;
        var end_y = rect_.attrs.y + rect_.attrs.height / 2;

        var arrow_ = new Konva.Arrow({
            points: [start_x, start_y, end_x, end_y],
            stroke: '#3f51b5',
            strokeWidth: 2,
            pointerLength: 5,
            pointerWidth: 5,
            fill: '#3f51b5'
        });

        key_text['arrows'].push(arrow_);
    }

    // 移动文字需要同时移动rect和arrow
    text_.on('dragmove', function () {
        rect_.setAttrs({
            'x': text_.attrs.x,
            'y': text_.attrs.y
        });
        rect_left_top.setAttrs({
            'x': rect_.attrs.x - 4,
            'y': rect_.attrs.y - 4
        });
        rect_left_bottom.setAttrs({
            'x': rect_.attrs.x - 4,
            'y': rect_.attrs.y + rect_.attrs.height - 4
        });
        rect_right_top.setAttrs({
            'x': rect_.attrs.x + rect_.attrs.width - 4,
            'y': rect_.attrs.y - 4
        });
        rect_right_bottom.setAttrs({
            'x': rect_.attrs.x + rect_.attrs.width - 4,
            'y': rect_.attrs.y + rect_.attrs.height - 4
        });

        if (arrow_) {
            arrow_.fire('myevent');
        }

        if (text_['arrows'] && text_['arrows'].length) {
            for (var i = 0; i < text_['arrows'].length; i++) {
                text_['arrows'][i].fire('myevent');
            }
        }

        // 记录节点的最新x,y，以便重新绘制时能记忆位置信息
        item['x'] = text_.attrs.x;
        item['y'] = text_.attrs.y;
    });

    text_.on('dblclick', function () {
        if (text_['selected'] && cur_item) {
            mdui.prompt('节点名称', '节点', function (text) {
                    text = text.toLowerCase();

                    if (cur_item && text && text != cur_item['key']) {
                        // 如果当前出于编辑状态
                        if (cur_item['key']) {
                            $.ajax({
                                'url': '/trainPlatform/update_node_name.do',
                                'data': {
                                    oldname: cur_item['key'],
                                    newname: text
                                },
                                'success': function (resp) {
                                    if (resp.success) {

                                    }
                                }
                            });
                        } else {
                            var parent_item = find_item_by_nid(data, cur_item['pnid']);

                            if (!parent_item) {
                                return;
                            }

                            $.ajax({
                                'url': '/trainPlatform/insert_node.do',
                                'data': {
                                    'root': parent_item['key'],
                                    'leaf': text,
                                    'rltp': 'InstanceOf'
                                }
                            });
                        }

                        cur_item['key'] = text;

                        cur_selected.fire('unselected');

                        cur_item = null;
                        cur_selected = null;

                        clear_selected(data);

                        // 清除界面
                        clear_screen();

                        iter(data);
                    }
                }, function (text) {
                },
                {
                    'confirmText': '确定',
                    'cancelText': '取消',
                    'defaultValue': cur_item['key']
                });
        }
    });

    text_.on('click', function (e) {
        console.log(e.button);

        if (text_['selected']) {
            text_['selected'] = false;

            rect_left_top.setAttr('opacity', 0);
            rect_right_top.setAttr('opacity', 0);
            rect_left_bottom.setAttr('opacity', 0);
            rect_right_bottom.setAttr('opacity', 0);

            layer.draw();

            cur_item = null;
            cur_selected = null;

            SynonymList([]);
        } else {
            if (cur_selected) {
                cur_selected.fire('unselected');
            }

            text_['selected'] = true;

            rect_left_top.setAttr('opacity', 1);
            rect_right_top.setAttr('opacity', 1);
            rect_left_bottom.setAttr('opacity', 1);
            rect_right_bottom.setAttr('opacity', 1);

            layer.draw();

            cur_selected = text_;
            cur_item = item;

            // 显示同义节点列表
            SynonymList(item['alias']);
        }
    });

    text_.on('unselected', function () {
        text_['selected'] = false;

        rect_left_top.setAttr('opacity', 0);
        rect_right_top.setAttr('opacity', 0);
        rect_left_bottom.setAttr('opacity', 0);
        rect_right_bottom.setAttr('opacity', 0);
    });

    document.getElementById('ctx-menu-edit').addEventListener('click', function (e) {
        if (text_['selected']) {
            text_.fire('dblclick');
        }
    });

    // 删除节点自身
    document.getElementById('ctx-menu-del-node').addEventListener('click', function (e) {
        if (text_['selected'] && cur_item) {
            if (cur_item['key']) {
                mdui.dialog({
                    title: '节点删除提醒',
                    content: '删除此节点将使此节点不再可见，确定删除吗?',
                    buttons: [
                        {
                            text: '取消'
                        },
                        {
                            text: '确认',
                            onClick: function (inst) {
                                $.ajax({
                                    'url': '/trainPlatform/delNode.do',
                                    'data': {
                                        'name': cur_item['key']
                                    },
                                    'success': function (resp) {
                                        if (resp.success) {
                                            $.each($('.knowledge_item'), function (i, e) {
                                                if ($(e).find('.mdui-chip-title').text() == cur_item['key']) {
                                                    $(e).remove();
                                                }
                                            });

                                            text_['selected'] = false;

                                            cur_item['hidden'] = true;

                                            cur_selected.fire('unselected');

                                            cur_item = null;
                                            cur_selected = null;

                                            clear_selected(data);

                                            // 清除界面
                                            clear_screen();

                                            iter(data);

                                            SynonymList([]);
                                        }
                                    }
                                });
                            }
                        }
                    ]
                });
            } else {
                text_['selected'] = false;
                cur_item['hidden'] = true;

                cur_selected.fire('unselected');

                cur_item = null;
                cur_selected = null;

                clear_selected(data);

                // 清除界面
                clear_screen();

                iter(data);

                SynonymList([]);
            }
        }
    });

    document.getElementById('ctx-menu-del').addEventListener('click', function (e) {
        if (text_['selected'] && cur_item) {
            var parent_item = find_item_by_nid(data, cur_item['pnid']);

            if (!parent_item) {
                return;
            }

            // 只有非根节点才能调用此过程
            if (cur_item['key']) {
                if (!parent_item) {
                    return;
                }

                mdui.dialog({
                    title: '节点删除提醒',
                    content: '本节点与父节点的关系删除不可恢复,确定要删除吗?',
                    buttons: [
                        {
                            text: '取消'
                        },
                        {
                            text: '确认',
                            onClick: function (inst) {
                                $.ajax({
                                    'url': '/trainPlatform/delete_node.do',
                                    'data': {
                                        'root': parent_item['key'],
                                        'leaf': cur_item['key']
                                    },
                                    'success': function (resp) {
                                        if (resp.success) {
                                            text_['selected'] = false;

                                            cur_item['hidden'] = true;

                                            cur_selected.fire('unselected');

                                            cur_item = null;
                                            cur_selected = null;

                                            clear_selected(data);

                                            // 清除界面
                                            clear_screen();

                                            iter(data);

                                            SynonymList([]);
                                        }
                                    }
                                });
                            }
                        }
                    ]
                });
            } else {
                text_['selected'] = false;
                cur_item['hidden'] = true;

                cur_selected.fire('unselected');

                cur_item = null;
                cur_selected = null;

                clear_selected(data);

                // 清除界面
                clear_screen();

                iter(data);

                SynonymList([]);
            }
        }
    });

    // 右键上下文菜单
    window.addEventListener('contextmenu', function (e) {
        e.preventDefault();

        if (text_['selected']) {
            $('#ctx-menu').css({
                'left': e.clientX,
                'top': e.clientY
            });
            inst.open();
        }
    });

    window.addEventListener('keydown', function (e) {
        if (!text_['selected']) {
            return;
        }

        // 新建同级节点,根节点不能创造同级节点
        if (e.keyCode == 13 && key_text) {
            var parent_item = find_item_by_nid(data, cur_item['pnid']);

            text_.fire('unselected');

            cur_selected = null;
            cur_item = null;

            // 清除数据结构中的选中状态
            clear_selected(data);

            // 向父节点追加一个子节点
            parent_item['value'].push({
                'key': '',
                'x': text_.attrs.x,
                'y': text_.attrs.y + 100,
                'nid': Math.floor(Math.random() * 10000 + 1),
                'pnid': parent_item['nid'],
                'selected': true,
                'alias': [],
                'value': []
            });

            // 清除界面
            clear_screen();

            // 重新绘制
            iter(data);
        } else if (e.keyCode == 9) {
            // 如果该节点自身还是空节点的话则不支持再引申出下一级
            if (!cur_item['key']) {
                return;
            }

            text_.fire('unselected');

            // 清除数据结构中的选中状态
            clear_selected(data);

            // 向该节点追加一个子节点
            cur_item['value'].push({
                'key': '',
                'x': text_.attrs.x + text_.getWidth() + 100,
                'y': text_.attrs.y,
                'nid': Math.floor(Math.random() * 10000 + 1),
                'pnid': cur_item['nid'],
                'selected': true,
                'alias': [],
                'value': []
            });

            cur_selected = null;
            cur_item = null;

            // 清除界面
            clear_screen();

            // 重新绘制
            iter(data);
        }

        if (e.keyCode == 13 || e.keyCode == 9) {
            e.preventDefault();
        }
    });

    if (arrow_) {
        arrow_.on('myevent', function () {
            arrow_.setAttrs({
                'points': [
                    key_text.attrs.x + key_text.getWidth(),
                    key_text.attrs.y + key_text.getHeight() / 2,
                    rect_.attrs.x,
                    rect_.attrs.y + rect_.attrs.height / 2
                ]
            });
        });
    }

    group.add(rect_);
    group.add(text_);
    group.add(rect_left_top);
    group.add(rect_left_bottom);
    group.add(rect_right_top);
    group.add(rect_right_bottom);

    if (arrow_) {
        group.add(arrow_);
    }

    layer.add(group);

    if (!key_text) {
        // text_.fire('click');
    }

    return text_;
}


var inst = new mdui.Menu('#open', '#menu');
var inst2 = new mdui.Menu('#open2', '#menu2');